<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="新建商品"
      left-text="返回"
      right-text="完成"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onSubmit"
    />

    <!-- 标题 -->
    <div class="typecenter">
      <h5 class="h5">基础信息</h5>
      <!-- 文件上传 -->
      <van-row>
        <van-col span="4"  style="display: flex;justify-content: center;align-items: center;height: 80px;">
          <div><span style="font-size: 14px;">商品图片</span></div>
        </van-col>
        <van-col span="2">
          
        </van-col>
        <van-col span="14">
          <van-uploader action="item/uploadImg" name="file" :after-read="afterRead" v-model="fileList" multiple :max-count="1" />
        </van-col>
      </van-row>


      <!-- 商品名称 -->
      <van-field
        v-model="itemObj.itemName"
        colon
        name="商品名称"
        label="商品名称"
        placeholder="商品名称"
        :rules="[{ required: true, message: '请填写商品名称' }]"
      />
      <!-- 商品价格 -->
      <van-field
        type="number"
        v-model="itemObj.itemPrice"
        colon
        name="商品价格"
        label="商品价格"
        placeholder="商品价格"
        :rules="[{ required: true, message: '请填写商品名称' }]"
      />

      <!-- 商品类型 -->
      <van-field
        readonly
        clickable
        name="picker"
        :value="value"
        label="商品分类"
        placeholder="点击选择商品分类"
        @click="showPicker = true"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          value-key="itemTypeName"
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>

      

      <!-- 规格 -->
      <van-row>
        <van-col span="8">
        </van-col>
        <van-col span="10">
        </van-col>
        <van-col span="6">
          <van-button 
            @click="addGuiGeIndex"
            color="linear-gradient(to right, #ff6034, #ee0a24)">
            建立规格
          </van-button>
        </van-col>
      </van-row>

      <van-row v-for="(index, i) in guigeindex" :key="index" style="margin-bottom: 15px;">
        <span>规格{{ index }}</span>
        <van-cell-group>
          <van-field v-model="values[i].type" label="规格类型" placeholder="如份量、辣度、容量、功能等" />
        </van-cell-group>
        <van-cell-group>
          <van-field v-model="values[i].value" label="规格值" placeholder="如辣度：不辣,微辣,中辣,特辣" />
        </van-cell-group>
      </van-row>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'


export default {
  name: 'newgroup',
  data(){
    return{
      values: [], // 用于存储每个文本框的值
      // 规格索引
      guigeindex:0,
      //规格对象
      guigeObj:{
        id:0,
        weightName:'',
        values:null,
        selectedValue:null,
      },
      //文件
      fileList:[],
      //商品对象
      itemObj:{
        //商家id
        shopId:this.$store.state.shop.shopId,
        //商品图片名称
        itemPicture:"",
        //类型id
        itemTypeId:null,
        //价格
        itemPrice:null,
        //商品名称
        itemName:"",
        //商品状态
        itemState:'0',
        //规格
        itemDetails:[],
      },
      shop:this.$store.state.shop,
      //分类选中的值
      value: '',
      //规格选中的值
      value2:'',
      //规格选中后再选中的值
      value3:'',
      //商品分类
      columns: [],
      //选规格
      columns2:['份量', '辣度', '', '绍兴', '湖州', '嘉兴', '金华', '衢州'],
      //选规格选中后的值
      columns3:['杭州', '宁波', '温州', '绍兴', '湖州', '嘉兴', '金华', '衢州'],
      //分类弹窗
      showPicker: false,
      //规格弹窗
      showPicker2:false,
      //规格选中后的值
      showPicker3:false
    };
  },
  methods:{
    addGuiGeIndex(){
      this.guigeindex++;
      // 在添加每次循环时，为values数组初始化一个空对象
      this.values.push({});
    },
    saveFormData() {
      const formData = [];
      for (let i = 0; i < this.values.length; i++) {
          formData.push({
            id: i + 1,
            values: [this.values[i].value],
            weightName: this.values[i].type,
            selectedValue: this.values[i].value.split(/[,，]/)[0]
          });
      }
      console.log(formData); // 打印格式化后的数据
      // 这里可以将`formData`发送到服务器进行保存或进行其他操作
      this.itemObj.itemDetails = JSON.stringify(formData);
    },
    //判断 类型是否有值
    isItemType(){

    },
    onChange(picker, values) {
      console.log(picker,values);
    },
    onChange2(picker, values) {
      console.log(picker,values);
    }, 
    //选规格
    onConfirm2(value){
      this.value2 = value;
      this.showPicker2 = false;
    },
    //选规格后
    onConfirm3(value){
      this.value3 = value;
      this.showPicker3 = false;
    },
    onClickLeft() {
      if (this.$route.query.itemType != null && this.$route.query.itemType != {} 
      &&this.$route.query.itemType != '') {
          this.$router.push({
          name:"group"
        })
        return;
      }
      this.$router.push({
        name:"item"
      })
    },
    //完成
    onSubmit(){
      this.saveFormData();
      console.log("添加商品后的对象");
      axios.defaults.headers['Content-type'] = 'application/x-www-form-urlencoded;charset=utf-8';
      axios.post("/api/item/add",this.itemObj).then(result =>{
        console.log(result.data);
      })
    },
    //选择文件回调
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file);
      
      //文件上传必须写通过formData对象
      const fromData = new FormData()
      fromData.append("file",file.file)
      //需要设置请求头为文件上传的form-data
      axios.post("/api/item/uploadImg",fromData,{
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then(result =>{
        //复制图片
        this.itemObj.itemPicture = result.data.data
        console.log(result.data);
      })
      console.log(file);
    },

    //类型选择后选择的值
    onConfirm(value) {
      this.value = value.itemTypeName;
      this.itemObj.itemTypeId = value.itemTypeId
      console.log(value.itemTypeId);
      this.showPicker = false;
    },
     //通过商家id查询全部商品类型
     getItemTypeByShopId(){
      //判断路由中参数是否为空
      if (Object.keys(this.$route.query).length > 0) {
        this.columns.push(this.$route.query.itemType)
        return;
      }
        axios.get("/api/item/itemType/getItemTypeListByShopId",
        {
          params:{
            shopId:this.shop.shopId
          }
        }).then(result =>{
          console.log(result.data.data);
          this.columns = result.data.data
          console.log(this.columns);
        })
    },
  },
  mounted() {
    console.log(this.$route)
    this.getItemTypeByShopId()
  },
  
}
</script>
  
<style scoped>
  .typecenter{
    width: 95%;
    margin: 0 auto;
  }
  .h5{
    margin-top: 20px;
  }
</style>
